﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace Simpletron
{
  public class SimpleApp
  {
    private List<int> instructions;

    private SimpleApp(string name)
	  {
      instructions = new List<int>();
      Name = name;
    }

    public int Size { get { return instructions.Count;} }

    public string Name { get; private set; }

    public int this[int index]
    {
      get { return instructions[index]; }
    }

    public void Add(int instruction)
    {
      instructions.Add(instruction);
    }

    public void Add(int opcode, int operand)
    {
      Add((opcode * 10000000) + operand);
    }

    public void Add(SimpletronOpCodes opcode, int operand)
    {
      Add((int)opcode, operand);
    }

    public void AddMany(int instruction, int count)
    {
      for (int i = 0; i < count; i++) Add(instruction);
    }

    public void AddMany(int opcode, int operand, int count)
    {
      for (int i = 0; i < count; i++) Add(opcode, operand);
    }

    public void AddMany(SimpletronOpCodes opcode, int operand, int count)
    {
      for (int i = 0; i < count; i++) Add(opcode, operand);
    }

    public static SimpleApp Load(FileStream stream) 
    {
      var name = "Some Name";
      var app = Create(name);
      app.Add(0);
      app.Add(0);
      app.Add(0);
      app.Add(0);
      app.Add(0);
      return app; 
    }
    
    public static SimpleApp Load(string path)
    {
      return Load(File.Open(path,FileMode.Open,FileAccess.Read)); 
    }

    public static SimpleApp Create(string name) 
    { 
      return new SimpleApp(name); 
    }

    public override string ToString()
    {
      int counter = 0;
      StringBuilder sb = new StringBuilder();

      instructions.ForEach(i => sb.AppendFormat("{0}\t{1}\t{2}\t{3}\n", 
        counter++, 
        i,
        ((SimpletronOpCodes)Enum.Parse(typeof(SimpletronOpCodes), ((int)(i / 10000000)).ToString())).ToString(),
        i % 10000000
        )
        );

      return sb.ToString();
    }
  }
}
